//
//  LoginWebViewController.swift
//  LCYWeiBo
//
//  Created by 李长友 on 16/9/2.
//  Copyright © 2016年 app. All rights reserved.
//

import UIKit
import SVProgressHUD

class LoginWebViewController: UIViewController {

    lazy var webView = UIWebView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupNavigationBar()
        
        setupWebView()
    }
}

// MARK: - 设置UI
extension LoginWebViewController {
    
    private func setupNavigationBar() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: #selector(LoginWebViewController.leftBarButtonClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .Plain, target: self, action: #selector(LoginWebViewController.rightBarButtonClick))
        
        title = "登录"
    }
    
    private func setupWebView() {
        
        webView.frame = UIScreen.mainScreen().bounds
        webView.delegate = self
        view.addSubview(webView)
        webView.backgroundColor = UIColor.whiteColor()
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(app_key)&redirect_uri=\(redirect_uri)"
        webView.loadRequest(NSURLRequest(URL: NSURL(string: urlString)!))
    }
}

// MARK: - 按钮点击事件
extension LoginWebViewController {
    
    @objc private func leftBarButtonClick() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func rightBarButtonClick() {
        
        let jsCode = "document.getElementById('userId').value='1606020376@qq.com';document.getElementById('passwd').value='haomage';"
        
        webView.stringByEvaluatingJavaScriptFromString(jsCode)
    }
}

// MARK: - Web view delegate
extension LoginWebViewController: UIWebViewDelegate {
    
    //webView加载开始
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    //webView加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //webView加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
    
    //webView加载之前
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard request.URL!.absoluteString.containsString("code=") else {
            return true
        }
        
        let code = request.URL!.absoluteString.componentsSeparatedByString("code=").last!
        
        loadAccessToken(code)

        return false
    }
}

// MARK: - 请求数据
extension LoginWebViewController {
    
    //请求accessToken
    private func loadAccessToken(code: String) {
        
        NetworkTools.shareInstance.loadAccessToken(code) { response in
            
            guard response.result.isSuccess else {
                debugLog(response.result.error)
                return
            }
            
            UserModel.shareInstance.setValueWithDictionary(response.result.value as! [String : AnyObject])
            self.loadUserInfo(UserModel.shareInstance)
            debugLog(response.result.value)
        }
    }
    
    //请求用户信息
    private func loadUserInfo(user: UserModel) {
        
        guard let access_token = user.access_token else {
             return
        }
        
        guard let uid = user.uid else {
            return
        }
        
        NetworkTools.shareInstance.loadUserInfo(access_token, uid: uid) { response in
            
            guard response.result.isSuccess else {
                debugLog(response.result.error)
                return
            }
            
            UserModel.shareInstance.setValueWithDictionary(response.result.value as! [String : AnyObject])
            
            UserViewModel.shareInstance.user = UserModel.shareInstance
            
            //归档
            NSKeyedArchiver.archiveRootObject(UserModel.shareInstance, toFile: UserViewModel.shareInstance.userPath)
//            debugLog(UserViewModel.shareInstance.userPath)
//            debugLog(response.result.value)
            
            UserViewModel.shareInstance.user = UserModel.shareInstance
            
            self.dismissViewControllerAnimated(false, completion: { 
                UIApplication.sharedApplication().keyWindow?.rootViewController = WelcomeViewController()
            })
        }
    }
}

















